// @ts-check
(function () {
    /**
     * 
     * @param {string} token 
     * @param {string} str 
     * 
     * @protected http://www.jshaman.com/protect.html
     * @returns {string}
     */
    var incrypt_account = function (token, str) {
        var bits = new Set(token.substring(4, 12).split('').map(function (n) { return parseInt(n, 16) }));
        var account = '';
        for (var i = 0; i < str.length; i++) {
            var c = str[i];
            while (bits.has(account.length)) {
                account += Math.floor(Math.random() * 36).toString(36);
            }
            account += c;
        }
        return account
    }

    var form = document.querySelector('form');
    /** @type { HTMLInputElement } */
    var token_input = form.querySelector('[name="token"]');
    var token = token_input.value

    /** @type { HTMLInputElement } */
    var name_input = form.querySelector('[name="name"]');
    /** @type { HTMLInputElement } */
    var pass_input = form.querySelector('[name="password"]');
    /** @type { HTMLInputElement } */
    var captcha_input = form.querySelector('[name="captcha"]');
    var error_show = document.getElementById('error-show');
    
    form.addEventListener('submit', function (e) {
        e.preventDefault();
        var str = btoa(JSON.stringify({
            name: name_input.value,
            password: pass_input.value,
        }, null, 1));
        
        var account = incrypt_account(token, str)
        var xhr = new XMLHttpRequest()
        xhr.addEventListener('readystatechange', function (e) {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    const res = JSON.parse(xhr.responseText);
                    token = res.token
                    if (res.error) {
                        error_show.innerText = res.error;
                    } else {
                        if (res.msg) {
                            alert(res.msg)
                        }
                        location.href = "{{query}}";
                    }
                }
            }
        })
        xhr.open(form.method, form.action)
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest',);
        xhr.send('token=' + token + '&account=' + account + '&captcha=' + captcha_input.value)
    })
})();